<?php
/**
 * Project: AIGC
 * Author: moufer <moufer@163.com>
 * Date: 2024/7/22 00:16
 */

namespace module\ai\library\channel\completion;

use module\ai\library\channel\abstract\Completion;

class BaiduCompletion extends Completion
{

    /**
     * @inheritDoc
     */
    protected function rawToData(): void
    {
        $raw = $this->rawData;
        if (isset($raw['error_code'])) {
            $code = (int)$raw['error_code'];
            list($message, $clear) = match ($code) {
                336104 => ['前置内容(system)不合法', true],
                default => [$raw['error_msg'], true],
            };
            $this->error($message, $raw['error_code'], $clear);
        }
        if (isset($raw['result'])) {
            $this->data['message'] = [
                'content' => $raw['result'],
                'role'    => 'assistant',
            ];
            $this->data['index'] = !empty($raw['sentence_id']) ? $raw['sentence_id'] : 0;
            $this->data['status'] = !$this->stream ? 'finish'
                : (!isset($raw['is_end']) ? 'finish' : ($raw['is_end'] ? 'finish' : 'receiving'));
            $this->data['finish_reason'] = $raw['finish_reason'] ?? '';
            $this->data['clear_receive'] = $raw['need_clear_history'] ?? false;
            if ($raw['usage']) {
                $this->data['tokens'] = [
                    'send_tokens'    => $raw['usage']['prompt_tokens'],
                    'receive_tokens' => $raw['usage']['completion_tokens'],
                    'total_tokens'   => $raw['usage']['total_tokens'],
                ];
            }
        }
    }
}